package com.orangelife.mobile.goodsOrder.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.curry.android.http.OrangeDataHandler;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.view.BadgeView;
import com.curry.orangelife.mobile.R;
import com.markupartist.android.widget.PullToRefreshListView;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.goodsOrder.adapter.GoodsOrderAdapter;
import com.orangelife.mobile.goodsOrder.biz.OrderBiz;
import com.orangelife.mobile.goodsOrder.biz.OrderHttp;
import com.orangelife.mobile.util.JsonReponseHandler;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 商品订单
 * Created by YangWei
 * on 2016/1/11.
 */
@Deprecated
public class GoodOrdersActivity extends OrangeLifeBaseActivity {

    @Bind(R.id.ib_title_left)
    LinearLayout ibTitleLeft;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.rl_title)
    RelativeLayout rlTitle;
    @Bind(R.id.tvAllOrder)
    TextView tvAllOrder;
    @Bind(R.id.textView2)
    TextView textView2;
    @Bind(R.id.rlAllOrder)
    RelativeLayout rlAllOrder;
    @Bind(R.id.tvTab1)
    TextView tvTab1;
    @Bind(R.id.indicator1)
    View indicator1;
    @Bind(R.id.tvTab2)
    TextView tvTab2;
    @Bind(R.id.indicator2)
    View indicator2;
    @Bind(R.id.tvTab3)
    TextView tvTab3;
    @Bind(R.id.indicator3)
    View indicator3;
    @Bind(R.id.tvTab4)
    TextView tvTab4;
    @Bind(R.id.indicator4)
    View indicator4;
    @Bind(R.id.tvTab5)
    TextView tvTab5;
    @Bind(R.id.indicator5)
    View indicator5;
    @Bind(R.id.llTabBar)
    LinearLayout llTabBar;
    @Bind(R.id.lv_my_order)
    PullToRefreshListView lvMyOrder;
    @Bind(R.id.tvNoBill)
    TextView tvNoBill;
    @Bind(R.id.llPropertyBillN)
    RelativeLayout llPropertyBillN;
    BadgeView bvTab1;
    BadgeView bvTab2;
    BadgeView bvTab3;
    BadgeView bvTab4;
    BadgeView bvTab5;
    // 订单状态(0 所有订单 1待付款 2待发货 3已发货 4已完成 5退款处理)
    public static final int ORDER_TYPE_WAIT_PAY = 0;
    public static final int ORDER_TYPE_WAIT_DELIVER = 1;
    public static final int ORDER_TYPE_HAS_DELIVER = 2;
    public static final int ORDER_TYPE_FINISH = 3;
    public static final int ORDER_TYPE_DRAWBACK = 4;

    private int pageSize = Constant.PAGE_SIZE_DEFAULLT;
    private int pageNo = Constant.PAGE_NO_DEFAULT;

    private GoodsOrderAdapter<Map<String, Object>> adapter;
    private Dialog dialog, dlgLoading;
    private int flags = 1;//分辨是刷新还是加载更多
    // TabLayout中的tab标题
    private String[] mTitles;
    private TextView[] tvTabs = new TextView[5];
    private BadgeView[] bvTabs = new BadgeView[5];
    private View[] indicators = new View[5];
    private int currentListType;
    private List<Map<String, Object>> list, list2;
    private Handler mHandler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_order);
        ButterKnife.bind(this);

        initTab();
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        OrderHttp.getOrderMsgNum(handler);
        pageNo=1;
        getMyGoodsOrderList();
    }

    private void initTab() {
        tvTabs[0] = tvTab1;
        tvTabs[1] = tvTab2;
        tvTabs[2] = tvTab3;
        tvTabs[3] = tvTab4;
        tvTabs[4] = tvTab5;
        bvTabs[0] = bvTab1;
        bvTabs[1] = bvTab2;
        bvTabs[2] = bvTab3;
        bvTabs[3] = bvTab4;
        bvTabs[4] = bvTab5;
        indicators[0] = indicator1;
        indicators[1] = indicator2;
        indicators[2] = indicator3;
        indicators[3] = indicator4;
        indicators[4] = indicator5;
        mTitles = getResources().getStringArray(R.array.order_title);
        for (int i = 0; i < mTitles.length; i++) {
            tvTabs[i].setText(mTitles[i]);
            initBadgeView(i, tvTabs[i]);
        }

    }

    private void initView() {
        tvTitle.setText("商品订单");
        tvNoBill.setText("您目前没有订单");
        mHandler = new Handler();
        currentListType = ORDER_TYPE_WAIT_PAY;//初始化待付款状态
        selectedTab();
        getDataFromServer();
        setAdapter();
        lvMyOrder.setPullLoadEnable(false);
        lvMyOrder.setAdapter(adapter);
        pullListView();

        adapter.setJump(new GoodsOrderAdapter.jumpInterface() {
            @Override
            public void pay(Map<String, Object> map) {
                OrderBiz.payOrder(map,GoodOrdersActivity.this,null);
            }

            @Override
            public void confirm(final String orderId) {
                final ConfirmDialog dialog = new ConfirmDialog(GoodOrdersActivity.this, "", "确认收货后将不再支持退款申请，\n" +
                        "是否确认收货？", "取消", "确认");
                dialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
                    @Override
                    public void doLeft() {
                        dialog.dismiss();
                    }

                    @Override
                    public void doRight() {
                        OrderHttp.postConfirmRequest(orderId, handler);
                    }
                });
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
            }

            @Override
            public void backGood(String applicationID) {
                OrderBiz.backGoods(applicationID,GoodOrdersActivity.this);
            }
        });

    }



    @OnClick({R.id.tvTab1, R.id.tvTab2, R.id.tvTab3, R.id.tvTab4, R.id.tvTab5,R.id.rlAllOrder})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvTab1:
                changeStatus(ORDER_TYPE_WAIT_PAY);
                break;
            case R.id.tvTab2:
                changeStatus(ORDER_TYPE_WAIT_DELIVER);
                break;
            case R.id.tvTab3:
                changeStatus(ORDER_TYPE_HAS_DELIVER);
                break;
            case R.id.tvTab4:
                changeStatus(ORDER_TYPE_FINISH);
                break;
            case R.id.tvTab5:
                changeStatus(ORDER_TYPE_DRAWBACK);
                break;
            case R.id.rlAllOrder:
                IntentHelper.getInstances().getIntent(this,AllOrderActivity.class);
                break;
        }
    }

    private void changeStatus(int listType) {
        getDataFromServer();
        pageNo = 1;
        list.clear();
        currentListType = listType;
        selectedTab();
        getMyGoodsOrderList();
    }

    /**
     * 设置适配器
     */
    private void setAdapter() {
        list = new ArrayList<Map<String, Object>>();
        list2 = new ArrayList<Map<String, Object>>();
        adapter = new GoodsOrderAdapter<Map<String, Object>>(this, list);
        lvMyOrder.setPullLoadEnable(false);
        lvMyOrder.setAdapter(adapter);
    }

    /**
     * 判断是否有订单显示无订单页面
     *
     * @param havebill
     */
    private void isNoBill(boolean havebill) {
        if (havebill) {
            lvMyOrder.setVisibility(View.VISIBLE);
            llPropertyBillN.setVisibility(View.GONE);
        } else {
            lvMyOrder.setVisibility(View.GONE);
            llPropertyBillN.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 下拉刷新的进度条
     */
    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(this,
                Constant.LOADING);
        dialog.show();
    }

    private void initBadgeView(int pos, TextView tv) {
        bvTabs[pos] = new BadgeView(this);
        bvTabs[pos].setTargetView(tv);
        bvTabs[pos].setBadgeCount(0);
        bvTabs[pos].setBadgeGravity(Gravity.CENTER);
        bvTabs[pos].setBackground(9, getResources().getColor(R.color.common_red));
        bvTabs[pos].setBadgeMargin(20, -10, 0, 0);
    }

    /**
     * 获取到消息数据后，转化为数组
     */
    private void setUnreadCounts(Map<String, Object> counts) {
        if (counts != null & counts.size() == bvTabs.length) {
            for (int i = 0; i < bvTabs.length; i++) {
                if (!StringUtil.isBlank(counts.get("count" + i).toString())) {
                    bvTabs[i].setBadgeCount(Integer.parseInt(counts.get("count" + i).toString()));
                } else {
                    bvTabs[i].setBadgeCount(0);
                }
            }
        }
    }

    /**
     * 切换tab样式
     */
    private void selectedTab() {
        for (int i = 0; i < tvTabs.length; i++) {
            if (i == currentListType) {
                tvTabs[i].setTextColor(getResources().getColor(R.color.title_orange));
                indicators[i].setVisibility(View.VISIBLE);
            } else {
                tvTabs[i].setTextColor(getResources().getColor(R.color.text_black));
                indicators[i].setVisibility(View.INVISIBLE);
            }
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 500:
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    DialogHelper.closeDialog(dlgLoading);
                    break;
                case 1001:
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    isLogin(dlgLoading);
                    break;
                case 1:
                    list2 = JsonReponseHandler.getListFromJson(
                            String.valueOf(msg.obj), adapter, dialog);
                    updateListView(list2);
                    break;
                case 2:
                    JSONObject json = null;
                    try {
                        json = new JSONObject(msg.obj.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Map<String, Object> data = OrangeDataHandler.getValueWithEntity(json);
                    setUnreadCounts(data);
                    break;
                default:
                    break;
            }
            if (dialog != null) {
                dialog.dismiss();
            }
        }

    };

    /**
     * 获取我的商品订单列表
     */
    private void getMyGoodsOrderList() {
        OrderHttp.getMyGoodsOrderList("", currentListType + 1,  pageSize, pageNo,handler);
    }


    /**
     * 下拉刷新列表
     */
    private void pullListView() {
        lvMyOrder.setXListViewListener(new PullToRefreshListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        // list.clear();
                        flags = 1;
                        pageNo = 1;
                        getMyGoodsOrderList();
                        onLoad();
                        adapter.setList(list);
                        adapter.notifyDataSetChanged();
                    }
                }, 2000);
            }

            @Override
            public void onLoadMore() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        flags = 0;
                        pageNo += 1;
                        getMyGoodsOrderList();
                        onLoad();
                        if (list != null) {
                            adapter.setList(list);
                            adapter.notifyDataSetChanged();
                        }
                    }
                }, 2000);
            }
        });
    }

    @SuppressWarnings("deprecation")
    private void onLoad() {
        lvMyOrder.stopRefresh();
        lvMyOrder.stopLoadMore();
        lvMyOrder.setRefreshTime(new Date().toLocaleString());
    }

    /**
     * 刷新 拉下列表
     *
     * @param list2
     */
    private void updateListView(List<Map<String, Object>> list2) {

        boolean havebill = false;
        if (list2 != null && list != null) {
            if (list2.size() == 0) {
                if (flags == 1) {
                    list.clear();
                    lvMyOrder.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = false;
                } else {
                    lvMyOrder.setPullLoadEnable(false);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = true;
                }
            } else {
                if (flags == 1) {
                    list.clear();
                    lvMyOrder.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = true;
                } else {
                    lvMyOrder.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    havebill = true;
                }
            }
        } else {
            lvMyOrder.setPullLoadEnable(false);
            havebill = false;
        }
        isNoBill(havebill);
    }





}
